package com.questionnaire.common.redis;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtil implements IRedisUtil{

    @Resource
    public   RedisTemplate redisTemplate;

    @Override
    public  ValueOperations<String,Object> setObjRedis(String key,Object value)  {
        ValueOperations<String,Object> cache=  redisTemplate.opsForValue();
        cache.set(key,value);
        return cache;
    }
    @Override
    public  Object getObjRedis(String key)  {
        return redisTemplate.opsForValue().get(key);
    }


    public Object delObjRedis(String key){
        return redisTemplate.opsForValue().getOperations().delete(key);
    }

    /**
     * 存储到redis中，并设置过期时间
     * @param key
     * @param value
     * @param timeout  过期时间(秒)
     * @return
     */
    public  ValueOperations<String,Object> setObjRedis(String key,Object value,long timeout)  {
        ValueOperations<String,Object> cache=  redisTemplate.opsForValue();
        cache.set(key,value,timeout, TimeUnit.SECONDS);
        return cache;
    }

    /**
     * 获取并删除
     * @param key
     * @return
     */
    public Object removeObjRedis(String key){
        Object obj = this.getObjRedis(key);
        this.delObjRedis(key);
        return obj;
    }
}
